package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisMessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.utils.SMSUtils;
import cn.itcast.utils.ValidateCodeUtils;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        //随机生成验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        try {
            //发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);//验证码发送失败
        }
        //如果验证码发送成功则需要存储到redis中进行后续校验，并设置有效时间，为了防止key冲突，在手机号后加入标志符表示这是验证码的key
        jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,3600,validateCode.toString());

        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);//验证码发送成功
    }

    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        //随机生成验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        try {
            //发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);//验证码发送失败
        }
        //如果验证码发送成功则需要存储到redis中进行后续校验，并设置有效时间，为了防止key冲突，在手机号后加入标志符表示这是验证码的key
        jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,3600,validateCode.toString());
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);//验证码发送成功
    }

}
